//
//  TstChooseContactVC.swift
//  TstChat
//
//  Created by wanghui on 2018/5/21.
//  Copyright © 2018年 daerwei. All rights reserved.
//

import UIKit
import Kingfisher
import Toast_Swift

private let collectionviewcell = "collectionviewcell"

class TstChooseContactVC: UIViewController {
    
    lazy var btn:UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.frame = CGRect(x: 0, y: 0, width: 60, height: 30)
        btn.setTitle("完成", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        btn.setTitleColor(UIColor.gray, for: .normal)
        btn.isEnabled = false
        btn.isUserInteractionEnabled = true
        btn.addTarget(self, action: #selector(rightbuttonTap(button:)), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    //顶部的占位view
    lazy var holderView:UIView = {
        let view = UIView()
        return view
    }()
    
    lazy var flowLayout : UICollectionViewFlowLayout = {
        let flt = UICollectionViewFlowLayout()
        flt.minimumLineSpacing = 10
        flt.minimumInteritemSpacing = 0
        flt.scrollDirection = UICollectionView.ScrollDirection.horizontal
        flt.itemSize = CGSize.init(width: 40, height: 40)
        flt.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)
        return flt
    }()
    
    lazy var collectionview: UICollectionView = {
        let collectionview = UICollectionView.init(frame:CGRect.zero,collectionViewLayout:flowLayout)
        collectionview.bounces = false
        collectionview.isPagingEnabled = true
        collectionview.showsHorizontalScrollIndicator = true
        collectionview.dataSource = self
        collectionview.delegate = self
        collectionview.register(TstChooseContactCollectionCell.self, forCellWithReuseIdentifier: collectionviewcell)
        return collectionview
    }()

    //搜索的图标
    lazy var searchimgview:UIImageView = {
        let searchimgview = UIImageView.init(image: UIImage.init(named: "tstChoosecontactFind"))
        return searchimgview
    }()
    
    //搜索
    lazy var searchlabel:UILabel = {
        let searchlabel = UILabel()
        searchlabel.text = "搜索"
        searchlabel.textColor = UIColor.lightGray.withAlphaComponent(0.7)
        searchlabel.font = UIFont.systemFont(ofSize: 13)
        return searchlabel
    }()
    
    lazy var tableView:UITableView = {
        let tableView = UITableView()
        tableView.separatorStyle = .singleLine
        tableView.tableFooterView = UIView.init(frame: CGRect.zero)
        tableView.dataSource = self as UITableViewDataSource
        tableView.delegate = self as UITableViewDelegate
        tableView.register(ContactCell.self, forCellReuseIdentifier: ContactCell.contactCellId)
        tableView.rowHeight = 55
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        tableView.isEditing = true
        tableView.allowsMultipleSelectionDuringEditing = true
        
        return tableView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData()
        setSection()
        setUI()
        //        self.addObserver(self, forKeyPath: "selectedList", options: .new, context: nil)
    }
    
    
    var contactList = [ChatContact]()
    let collation = UILocalizedIndexedCollation.current()
    var sectionsArray: [[ChatContact]] = [[ChatContact]]()
    var selectedList = [ChatContact]() {
        didSet {
            self.onSelectChanged()
        }
    }
    
    private var keysArray:[String] = []
    
    let service = ContactService()
    func loadData() {
        DispatchQueue.global().async {
            self.contactList = self.service.getContactList()
            if self.contactList.count > 0 {
                DispatchQueue.main.async {
                    self.setSection()
                }
            }
        }
    }

    func setSection(){
        UILocalizedIndexedCollation.getCurrentKeysAndObjectsData(needSortArray: contactList, collationStringSelector: #selector(getter: ChatContact.displayName)) { (dataArray,titleArray) in
                    self.sectionsArray = dataArray
                    self.keysArray    = titleArray
                    self.tableView.reloadData()
                }
    }
    
    //设置UI
    func setUI(){
        self.title = "选择联系人"
        self.view.backgroundColor = .systemBackground
        self.view.addSubview(tableView)
        self.view.addSubview(holderView)
        
        holderView.snp.makeConstraints { (make) in
            if #available(iOS 11, *) {
                make.top.equalTo(self.view.safeAreaLayoutGuide)
            } else {
                make.top.equalToSuperview()
            }
            make.left.equalToSuperview().offset(0)
            make.right.equalToSuperview().offset(0)
            make.height.equalTo(60)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(holderView.snp.bottom)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        self.holderView.addSubview(collectionview)
        collectionview.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(5)
            make.top.equalToSuperview().offset(0)
            make.bottom.equalToSuperview().offset(0)
            make.right.equalToSuperview().offset(-5)
        }
        
        let setupgroup = UIBarButtonItem(customView: btn)
        let spacertwo = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        spacertwo.width = -5
        self.navigationItem.rightBarButtonItems = [spacertwo, setupgroup]
    }
    
    @objc func buttonTap(button:UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func rightbuttonTap(button:UIButton) {
        let service = GroupService()
        var ids = [Int]()
        for chatContact in self.selectedList {
            ids.append(chatContact.userId)
        }
        self.view.makeModalToastActivity(.center)
        do {
            try service.createNewGroup(name: nil, createUserId: AppStatusManager.instance.userLoginStatus.1 ?? 0, ids: ids) { (success, msg, groupId) in
                if success {
                    DispatchQueue.main.async {
                        self.view.hideModalToastActivity()
                        let chatVc = ChatVC()
                        chatVc.chatType = ChatType.group
                        chatVc.sessionServerId = groupId
                        chatVc.sessionName = "群聊"
                        chatVc.hidesBottomBarWhenPushed = true
                        self.navigationController?.popViewController(animated: true)
                        self.navigationController?.pushViewController(chatVc, animated: true)
                    }
                } else {
                    DispatchQueue.main.async {
                        self.view.hideModalToastActivity()
                        self.view.makeToast(msg,duration:1,position:.center)
                    }
                }
            }
        } catch {
            print(error)
            DispatchQueue.main.async {
                self.view.hideModalToastActivity()
                self.view.makeToast("创建群聊失败",duration:1,position:.center)
            }
        }
    }
}

//扩展

extension TstChooseContactVC:UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate  {
    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: ContactCell.contactCellId, for: indexPath) as! ContactCell
        let userNameInSection = sectionsArray[indexPath.section]
        let contact = userNameInSection[indexPath.row]
        let kBtnGreen = RGBA(r: 0.15, g: 0.67, b: 0.16, a: 1.00)
        cell.tintColor = kBtnGreen
        cell.selectionStyle = .blue
        cell.nameLabel.text = contact.displayName
        
        cell.headimage.kf.setImage(with: Common.avatarUrl(contact.avatar ?? "") ?? URL(string: "localhost")!, placeholder: #imageLiteral(resourceName: "defaultAvatar"),options: [.processor(CryptorProcessor())])
        cell.tagbutton.isHidden = true
        
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return keysArray.count
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return keysArray[section]
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 23
    }
    
    //设置索引标题
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return keysArray
    }
    
    //关联搜索
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        if index == 0{
            tableView.setContentOffset(CGPoint.zero, animated: false)
            return 0
        }
        return index
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if sectionsArray.count == 0 {
            return 0
        }
        return sectionsArray[section].count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let userNameInSection = sectionsArray[indexPath.section]
        let contact = userNameInSection[indexPath.row]
        contact.indexPath = indexPath
        selectedList.append(contact)
        let collectIndex = IndexPath.init(row: (selectedList.count - 1), section: 0)
        self.collectionview.insertItems(at: [collectIndex])
        self.collectionview.scrollToItem(at: collectIndex, at: .right, animated: true)
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let userNameInSection = sectionsArray[indexPath.section]
        let contact = userNameInSection[indexPath.row]
        if let index = selectedList.index(of: contact) {
            selectedList.remove(at: index)
            let collectIndex = IndexPath.init(row: (index), section: 0)
            self.collectionview.deleteItems(at: [collectIndex])
        }
    }
}

extension TstChooseContactVC{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return selectedList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let contact = selectedList[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionviewcell, for: indexPath) as! TstChooseContactCollectionCell
        cell.headimage.kf.setImage(with: Common.avatarUrl(contact.avatar ?? "") ?? URL(string: "localhost")!, placeholder: #imageLiteral(resourceName: "defaultAvatar"),options: [.processor(CryptorProcessor())])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let contact = selectedList[indexPath.row]
        selectedList.remove(at: indexPath.row)
        self.collectionview.deleteItems(at: [indexPath])
        if let tableIndexPath = contact.indexPath {
            self.tableView.deselectRow(at: tableIndexPath, animated: true)
        }
    }
    
    func onSelectChanged() {
        if selectedList.count > 0 {
            btn.isEnabled = true
            btn.setTitle("完成(\(selectedList.count))", for: .normal)
            btn.setTitleColor(RGBA(r: 0.15, g: 0.67, b: 0.16, a: 1.00), for: .normal)
        } else {
            btn.isEnabled = false
            btn.setTitle("完成", for: .normal)
            btn.setTitleColor(UIColor.gray, for: .normal)
        }
    }
}

